package com.yzmoney.wechat.util;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.util.JsonUtils;
import com.yzmoney.wechat.model.general.WechatJsSDKConfig;
import org.apache.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by DOVE on 2015/8/29.
 */
public class WechatUtils {
    private static Logger logger = Logger.getLogger(WechatUtils.class);

    private static String appId = PropertyUtils.getValue("APPID", "", Constants.GZH_PATH);

    private static String nonce = PropertyUtils.getValue("TOKEN", "", Constants.GZH_PATH);

    public static WechatJsSDKConfig getJsSDKConfig(String jsToken, String url) {
        String timestamp = String.valueOf((new Date().getTime()));
        WechatJsSDKConfig config = new WechatJsSDKConfig(appId, timestamp, nonce);
        String array[] = new String[]{
                "jsapi_ticket=" + jsToken,
                "timestamp=" + timestamp,
                "noncestr=" + nonce,
                "url=" + url
        };
        logger.info("----->>> 参数:" + JsonUtils.toJson(array));
        StringBuffer sb = new StringBuffer();
        //字符排序
        Arrays.sort(array);

        for (int i = 0, arrayLength = array.length; i < arrayLength; i++) {
            sb.append(array[i]);
            if (i < (arrayLength - 1)) {
                sb.append("&");
            }
        }
        String str = sb.toString();
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] digest = md.digest(str.getBytes());
        String outerStr = byteToString(digest);
        config.setSignature(outerStr);
        return config;
    }

    /**
     * byte[] 转 String
     *
     * @param digest
     * @return
     */
    public static String byteToString(byte[] digest) {
        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }
}
